package com.atguigu.flink.chapter07.state;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink04_Keyed_State_Value {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env
                .socketTextStream("hadoop162", 9999)
                .map(line ->{
                    String[] strings = line.split(",");
                    return new WaterSensor(
                            strings[0],
                            Long.valueOf(strings[1]),
                            Integer.valueOf(strings[2]));
                })

                .keyBy(WaterSensor::getId)

                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private ValueState<Integer> lastVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVcState", Integer.class));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        Integer currentVc = value.getVc();
                        //从状态中获取值，如果状态中如果没有值， 则是null
                        Integer lastVc = lastVcState.value();
                        if (lastVc!= null){
                            if (lastVc> 10 && currentVc>10) {
                                out.collect(ctx.getCurrentKey()+ " 连续两次水位超过10,红色预警");
                            }
                        }
                        //更新状态，覆盖
                        lastVcState.update(currentVc);
                    }
                })

                .print();


        env.execute();
    }


}
